﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Threading.Tasks;
using System.Diagnostics;

/// <summary>
/// Summary description for DraftHub
/// </summary>
public class DraftHub : Hub
{

    private readonly static ConnectionMapping<string> connections =
       new ConnectionMapping<string>();
      private ChatRepository _repository;

    public DraftHub(){
         _repository = ChatRepository.GetInstance();
    }

    public void Send(string name, string message)
    {
        // Call the broadcastMessage method to update clients.

        Clients.All.broadcastMessage(name, message);
    }

    public void SendPick(string name, string pick)
    {
        string message = "has drafted " + pick + "!";
        Clients.All.broadcastPick(name, message);
    }

    public void SendNotifications()
    {
        Clients.Others.receiveNotification();
    }

     public void Joined()
        {
            ChatUser user = new ChatUser()
            {
                //Id = Context.ConnectionId,                
                Id = Guid.NewGuid().ToString(),
                Username = Clients.Caller.username
            };
            _repository.Add(user);
            _repository.AddMapping(Context.ConnectionId, user.Id);
            Clients.All.joins(user.Id, Clients.Caller.username, DateTime.Now);
        }

        /// <summary>
        /// Invoked when a client connects. Retrieves the list of all currently connected users
        /// </summary>
        /// <returns></returns>
        public ICollection<ChatUser> GetConnectedUsers()
        {
            return _repository.Users.ToList<ChatUser>();
        }


    //public override Task OnConnected()
    //{
    //    string name = Context.User.Identity.Name;

    //    connections.Add(name, Context.ConnectionId);

    //    return base.OnConnected();
    //}

    public override Task OnDisconnected()
    {
        string userId = _repository.GetUserByConnectionId(Context.ConnectionId);
        if (userId != null)
        {
            ChatUser user = _repository.Users.Where(u => u.Id == userId).FirstOrDefault();
            if (user != null)
            {
                _repository.Remove(user);
                return Clients.All.leaves(user.Id, user.Username, DateTime.Now);
            }
        }

        return base.OnDisconnected();
    }

    //public override Task OnReconnected()
    //{
    //    string name = Context.User.Identity.Name;

    //    if (!connections.GetConnections(name).Contains(Context.ConnectionId))
    //    {
    //        connections.Add(name, Context.ConnectionId);
    //    }

    //    return base.OnConnected();
    //}

    
}